import sys
from urllib.request import urlopen, Request
from urllib.parse import urlencode
import ssl
import base64
import json


class ImgCaption():
    
    def __init__(self):
        pass
    
    def img2txt(self, img_path):
        host = 'https://im2txt.xiaohuaerai.com'
        path = '/im2txt'
        method = 'POST'
        appcode = '8dc8f13acf5e422f8c74b1c35c523d16'
        querys = ''
        bodys = {}
        url = host + path

        with open(img_path, "rb") as image_file:
            encoded_string = base64.b64encode(image_file.read())
            bodys['src'] =  encoded_string
        post_data = urlencode(bodys).encode("utf-8")
        request = Request(url, post_data)
        request.add_header('Authorization', 'APPCODE ' + appcode)
        # 根据API的要求，定义相对应的Content-Type
        request.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        response = urlopen(request, context=ctx)
        content = response.read()
        if (content):
            return json.loads(content.decode("utf-8"))['msg']
            
            
if __name__ == "__main__":
    cap = ImgCaption()
    print(cap.img2txt("test001.jpg"))